package com.blockmeta.bbs.immodule.corebean;


import android.os.Bundle;

import com.blockmeta.bbs.immodule.corebean.Impl.ImMetaManager;

import java.util.concurrent.ConcurrentLinkedQueue;

public class MsgWorker extends Thread {
    protected ConcurrentLinkedQueue<QuePkt> m_msgQueue;
    protected ImMetaManager.IMsgEventListener m_imMsgListener = null;

    public MsgWorker() {
        m_msgQueue = new ConcurrentLinkedQueue<QuePkt>();
        setDaemon(true);
        start();
    }

    @Override
    public void run() {
        while (true) {
            QuePkt pkt = m_msgQueue.poll();

            if (pkt == null) {
                waitQueState();
                continue;
            } else {
                onFireEvent(pkt);
            }
        }
    }

    public void setPacketEventListener(ImMetaManager.IMsgEventListener listener) {
        m_imMsgListener = listener;
    }

    public void dispatch(String type, Bundle packet) {
        QuePkt pkt = new QuePkt(type, packet);

        m_msgQueue.add(pkt);
        notifyQueState(pkt);
    }

    protected synchronized void notifyQueState(QuePkt pkt) {
        notify();
    }

    protected synchronized void waitQueState() {
        try {
            wait();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    protected void onFireEvent(QuePkt pkt) {
        if (m_imMsgListener != null) {
            m_imMsgListener.onPacket(pkt.m_nType, pkt.m_objPacket);
        }
    }

    protected class QuePkt {
        public String m_nType;
        public Bundle m_objPacket;

        public QuePkt(String type, Bundle packet) {
            m_nType = type;
            m_objPacket = packet;
        }
    }
}
